var express = require('express');
var router = express.Router();
var mongo=require('../bin/model/mongo_docks');
/* GET home page. */
router.get('/', function(req, res, next) {
  res.sendfile('./views/index.html');
});

router.post('/query',function(req, res, next){
  if (req.body.type == 'extent') {
    var regionid = req.body.regionid;
    var promise = mongo.extentModel.findOne({'regionid': regionid}, {_id: 0, boundary: 1}).exec();
    var final = {};
    promise.then(function (division) {
      final.extent = division.toJSON();
      return mongo.wharfModel.find({'xzqdm': regionid}, {_id: 0}).sort({status_name: 1, xh: 1}).exec();
    }).then(function(wharfs){
      final.data = wharfs;

      res.send(final);
    });
  }else{
    next();
  }
})

router.post('/query',function(req, res, next){
  if (req.body.type == 'name') {
    var name = req.body.name;
    // var con = '/' + name + '/';
    mongo.wharfModel.find({name : { $regex: name}}, {_id: 0}, {sort: {xzqdm: 1, status_name: 1, xh: 1}}, function(err, results){
      if(!err){
        res.json(results);
      }
    });
  }else{
    next();
  }
})

router.get('/docks',function(req,res){
  mongo.wharfModel.find({xzqdm: '340800'},{'_id':0},function(err,docks){
    if(!err){
      res.json(docks);
    }
  })
})

router.get('/query/regexSearch/:defaultUrl',function(req,res){
  var pattern = req.params.defaultUrl;
    var con = '^' + pattern;
    mongo.wharfModel.find({name: RegExp(con)},{'_id':0},function(err,dock){
      if(!err){
        res.json(dock)
      }
    });
    
})

router.get('/dock/:defaultUrl',function(req,res){
  var id = parseInt(req.params.defaultUrl);
  console.log(id);
    mongo.wharfModel.find({'xh': id},{'_id':0},function(err,dock){
      if(!err){
        res.json(dock);
      }
    });
    
})



module.exports = router;
